package com.lianxi.controller;


import com.lianxi.pojo.Article;
import com.lianxi.pojo.BaseArticle;
import com.lianxi.pojo.Category;
import com.lianxi.service.ArticleService;
import com.lianxi.service.CategoryService;
import com.lianxi.service.LoginService;
import com.lianxi.utils.CommonResult;
import com.lianxi.utils.CurrentUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@Api(value = "文章的controller", tags = {"操作文章接口"})
public class ArticleController {

    @Autowired
    private ArticleService articleService;


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private LoginService loginService;


    @PostMapping("/isadmin")
    @ApiOperation("是否为管理员")
    public CommonResult isAdmin() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Boolean isAdmin=false;
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            System.out.println(authority.toString());
            if(authority.toString().equals("超级管理员")){
                isAdmin=true;
            }
        }
        return CommonResult.success(isAdmin);
    }

    @GetMapping("/getallarticle")
    @ApiOperation("查看所有发表的文章")
    public CommonResult getAllArticle(
                                      @RequestParam(defaultValue = "") Integer cid,
                                      @RequestParam(defaultValue = "") String title,
                                      @RequestParam(defaultValue = "1") int current,
                                      @RequestParam(defaultValue = "5") int size) {
        Map<String, Object> map = articleService.getAllArticle(cid,title,current, size);
        if (!map.isEmpty()) {
            return CommonResult.success(map);
        }
        return CommonResult.failNoDatas();
    }


    @GetMapping("/getpubartbyid")
    @ApiOperation("发表箱---自己的文章")
    public CommonResult getPubArtById(@RequestParam(value = "title",defaultValue = "") String title,
                                      @RequestParam(defaultValue = "1") int current,
                                      @RequestParam(value = "size", defaultValue = "5") int size)
    {
        Map<String, Object> map = articleService.getArtByUid(title,1, current, size);
        if (!map.isEmpty()) {
            return CommonResult.success(map);
        }
        return CommonResult.failNoDatas();
    }


    @GetMapping("/getdraartbyid")
    @ApiOperation("草稿箱---自己的文章")
    public CommonResult getDraArtById(@RequestParam(value = "title",defaultValue ="") String title,
                                      @RequestParam(defaultValue = "1") int current,
                                      @RequestParam(value = "size", defaultValue = "5") int size) {

        Map<String, Object> map = articleService.getArtByUid(title,2, current, size);
        if (!map.isEmpty()) {
            return CommonResult.success(map);
        }
        return CommonResult.failNoDatas();
    }


    @GetMapping("/getrecartbyid")
    @ApiOperation("回收站---自己的文章")
    public CommonResult getRecArtById(@RequestParam(value = "title",defaultValue = "") String title,
                                      @RequestParam(defaultValue = "1") int current,
                                      @RequestParam(value = "size", defaultValue = "5") int size) {
        Map<String, Object> map = articleService.getArtByUid(title,3, current, size);
        if (!map.isEmpty()) {
            return CommonResult.success(map);
        }
        return CommonResult.failNoDatas();
    }


    @PostMapping("/addarticletodra")
    @ApiOperation("添加文章到草稿箱")
    public CommonResult addArticleToDra(@RequestBody BaseArticle baseArticle) {
        int result = articleService.addArticleToDra(baseArticle);
        if (result <= 0) {
            return CommonResult.failHaveData(result);
        }
        return CommonResult.success(result);
    }

    @PostMapping("/addarticletopub")
    @ApiOperation("添加文章到发表")
    public CommonResult addArticleToPub(@RequestBody BaseArticle baseArticle) {
        int result = articleService.addArticleToPub(baseArticle);
        if (result <= 0) {
            return CommonResult.failHaveData(result);
        }
        return CommonResult.success(result);
    }

    @GetMapping("/getartbyid")
    @ApiOperation("aid获取文章信息")
    public CommonResult getOneArt(Integer aid) {
        Article oneArt = articleService.getOneArt(aid);
        if (oneArt != null) {
            return CommonResult.success(oneArt);
        } else {
            return CommonResult.failNoDatas();
        }
    }

    @PutMapping("/updateart")
    @ApiOperation("保存修改")
    public CommonResult updateArt(@RequestBody BaseArticle baseArticle) {
        int result = articleService.updateArt(baseArticle);
        if (result <= 0) {
            return CommonResult.failHaveData(result);
        }
        return CommonResult.success(result);
    }


    @PostMapping("/dratopub")
    @ApiOperation("已经在草稿箱，保存修改，到发表")
    public CommonResult DraTopub(@RequestBody BaseArticle baseArticle) {
        int result = articleService.DraTopub(baseArticle);
        if (result <= 0) {
            return CommonResult.failHaveData(result);
        }
        return CommonResult.success(result);
    }

    @PostMapping("/uploadimage")
    public CommonResult uploadImage(HttpServletRequest request, MultipartFile photo) throws IOException {
        String pathName = "E:\\images\\";
        File filePath = new File(pathName);
        if (!filePath.exists()) {
            filePath.mkdir();
        }
        if (!photo.isEmpty()) {
            //原始图片名字
            String str = photo.getOriginalFilename();
            //得到后缀名
            String str1 = str.substring(0, str.indexOf("."));
            String str2 = str.substring(str1.length() + 1, str.length());
            //uuid生成随机名,得到存入的图片地址
            String replace = UUID.randomUUID().toString().replace("-", "");
            String imageName = replace + "." + str2;
            //得到地址
            String serverName = request.getServerName();
            //得到端口号
            int serverPort = request.getServerPort();
            //上传图片
            photo.transferTo(new File(pathName + imageName));
            //拼接图片地址
            String address = "http://" + serverName + ":" + serverPort + "/" + "images/" + imageName;
            return CommonResult.success(address);
        }
        return CommonResult.error("上传失败");
    }

    @DeleteMapping("/delearticle")
    @ApiOperation("真删除--回收站")
    public CommonResult deleArticle(int[] aids) {
        int result = articleService.deleArticle(aids);
        if (result < 0) {
            return CommonResult.fail();
        } else {
            return CommonResult.success(result);
        }
    }

    @PutMapping("/delefake")
    @ApiOperation("假删除")
    public CommonResult deleFake(Integer aid) {
        int result = articleService.deleFake(aid);
        if (result <= 0) {
            return CommonResult.fail();
        } else {
            return CommonResult.success(result);
        }
    }

    @PutMapping("/rectores/{aid}")
    @ApiOperation("还原---回收站")
    public CommonResult recToRes(@PathVariable("aid") Integer aid) {
        int result = articleService.recToRes(aid);
        if (result <= 0) {
            return CommonResult.fail();
        } else {
            return CommonResult.success(result);
        }
    }

    @PutMapping("/getartbycid")
    @ApiOperation("栏目cid-获取文章")
    public CommonResult getArtbycid(@RequestParam(value = "cid",defaultValue = "") Integer cid,
                                    @RequestParam(defaultValue = "1") int current,
                                    @RequestParam(value = "size", defaultValue = "5") int size) {
        Map<String, Object> map = articleService.getArtByCid(cid, current, size);
        if (!map.isEmpty()) {
            return CommonResult.success(map);
        }
        return CommonResult.failNoDatas();
    }

    @GetMapping("/gethotlist")
    @ApiOperation("获取最热文章")
    public CommonResult  getHotArt(){
        List<Article> hotArt = articleService.getHotArt();
        if (hotArt.size()>0&&hotArt!=null){
            return CommonResult.success(hotArt);
        }else {
            return CommonResult.error("最热列表获取失败");
        }
    };

    @GetMapping("/getcateartnum")
    @ApiOperation("首页-栏目列表")
    public CommonResult  getCateArtNum(){
        List<Category> cateArtNum = categoryService.getCateArtNum();
        if (cateArtNum.size()>0&&cateArtNum!=null){
            return CommonResult.success(cateArtNum);
        }else {
            return CommonResult.error("最热列表获取失败");
        }
    };

}
